package com.guangbao.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.guanbao.entity.ResponseMessage;
import com.guanbao.entity.User;
import com.guangbao.service.UserService;
import com.guangbao.service.impl.UserServiceImpl;
import com.guangbao.utils.TokenUtil;

public class UserHandler extends HttpServlet{
	
	private UserService userService = new UserServiceImpl();
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("text/json;charset=utf-8");
		
		if(!auth(req,resp)) return;
		
		String op = req.getParameter("op");
		switch (op.toLowerCase()) {
		case "getall":
			getAllUser(req,resp);
			break;
		case "add":
			addUser(req, resp);
			break;
		case "update":
			updateUser(req, resp);
			break;
		case "getbyid":
			getUserById(req, resp);
			break;
		case "delbyid":
			delUserById(req,resp);
			break;
		default:
			notSupport(req,resp);
			break;
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	
	private void notSupport(HttpServletRequest req,HttpServletResponse resp) {
		try {
			Gson gson = new Gson();
			ResponseMessage resM = new ResponseMessage();
			resM.setStatus(ResponseMessage.getStatusError());
			resM.setMsg("不支持此操作");
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private boolean auth(HttpServletRequest req,HttpServletResponse resp) {
		try {
			
			String token = req.getHeader("Authorization");
			
			if(token == null || token.trim().isEmpty()||TokenUtil.verify(token)== null) {
				Gson gson = new Gson();
				ResponseMessage resM = new ResponseMessage();
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("非法访问");
				resp.getWriter().write(gson.toJson(resM));
				resp.getWriter().close();

				return false;
			}
			
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		return true;
	}
	
	private void getAllUser(HttpServletRequest req,HttpServletResponse resp) {
		try {
			Gson gson = new Gson();
			ResponseMessage resM = new ResponseMessage();
			List<User> users = userService.getAllUser();
			
			
			if(users.size()>0) {
				resM.setStatus(ResponseMessage.getStatusOk());
				resM.setMsg("查询成功");
				resM.setData(users);
			}else {
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("没有数据");
			}
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void getUserById(HttpServletRequest req,HttpServletResponse resp) {
		try {
			Gson gson = new Gson();
			ResponseMessage resM = new ResponseMessage();
			
			Integer id = Integer.parseInt(req.getParameter("id"));
			User user = userService.getUserById(id);
			
			if(user != null) {
				resM.setStatus(ResponseMessage.getStatusOk());
				resM.setMsg("查询成功");
				resM.setData(user);
			}else {
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("没有数据");
			}
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void delUserById(HttpServletRequest req,HttpServletResponse resp) {
		try {
			Gson gson = new Gson();
			ResponseMessage resM = new ResponseMessage();
			
			Integer id = Integer.parseInt(req.getParameter("id"));
			Boolean flag  = userService.removeUser(id);
			
			if(flag) {
				resM.setStatus(ResponseMessage.getStatusOk());
				resM.setMsg("删除成功");
			}else {
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("删除失败");
			}
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}
	
	private void addUser(HttpServletRequest req,HttpServletResponse resp) {
		Gson gson = new Gson();
		ResponseMessage resM = new ResponseMessage();
		try {
			String postJson = getJson(req);
			
			User user = gson.fromJson(postJson, User.class);
			
			Boolean flag = userService.saveUser(user);
			
			if(flag) {
				resM.setStatus(ResponseMessage.getStatusOk());
				resM.setMsg("新增成功");
			}else {
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("新增失败");
			}
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
	}
	
	private void updateUser(HttpServletRequest req,HttpServletResponse resp) {
		Gson gson = new Gson();
		ResponseMessage resM = new ResponseMessage();
		try {
			String postJson = getJson(req);
			
			User user = gson.fromJson(postJson, User.class);
			
			Boolean flag = userService.editUser(user);
			
			if(flag) {
				resM.setStatus(ResponseMessage.getStatusOk());
				resM.setMsg("修改成功");
			}else {
				resM.setStatus(ResponseMessage.getStatusError());
				resM.setMsg("修改失败");
			}
			resp.getWriter().write(gson.toJson(resM));
			resp.getWriter().close();
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		
	}
	
	private String getJson(HttpServletRequest req) {
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(req.getInputStream(),"utf-8"));

			String line = null;

			StringBuilder sb = new StringBuilder();

			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}